package com.x.aoki.order.controller;

import com.x.aoki.common.pojo.Payment;
import com.x.aoki.common.utils.CR;
import com.x.aoki.order.loadbalance.MyLB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 主控制器类
 *
 * @author caoy
 * @date 2025-02-14 16:14:41
 */
@RestController
public class OrderController {
    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    // public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://x-payment-provider";

    @Autowired
    private RestTemplate restTemplate;

    // @Resource
    // private MyLB myLB;
    // @Resource
    // public DiscoveryClient discoveryClient;

    @PostMapping("/order/payment/create")
    public CR create(@RequestBody Payment payment) {
        log.info("===== 订单服务调用支付服务开始 =====");
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CR.class);
    }

    @GetMapping(value = "/order/payment/get/{id}")
    public CR getPayment(@PathVariable("id") Long id) {
        log.info("===== 订单服务根据传入的 ID 调用支付服务开始 =====");
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CR.class);
    }

    /**
     * 这个方法需要使用 MyLB类趋势线自定义的负载均衡
     * @return
     */
    // @GetMapping("/order/lb")
    // public String getPaymentByMyLB() {
    //     List<ServiceInstance> instances = discoveryClient.getInstances("X-PAYMENT-PROVIDER");
    //     if (instances.isEmpty() || instances.size() <= 0) {
    //         return null;
    //     }
    //
    //     ServiceInstance serviceInstance = myLB.serviceInstance(instances);
    //     return restTemplate.getForObject(serviceInstance.getUri() + "/payment/lb", String.class);
    // }

    @GetMapping("/order/payment/zipkin")
    public String paymentZipkin() {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin", String.class);
    }
}
